home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: why is this an infinite loop?
- Date: 19 Jan 1996 23:07 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <19JAN199623075074@erich.triumf.ca>
- References: <4dp9p5$jm2@news1.wolfe.net>
- NNTP-Posting-Host: erich.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4dp9p5$jm2@news1.wolfe.net>, neus@wolfenet.com (Bill Campbell) writes...
- >Beginning c student can't figure out why this small function to read in a
- >value for the variable x causes an infinite loop when it receives unexpected
- >input.
- >
- >double get_x()
- >{
- > int test;
- > double x;
- >
- > printf("Enter a numeric value for x: ");
- >
- > while(scanf("%lf", &x) != 1)
-
- When scanf() is looking for numbers, it is _extremely_ intolerant of unexpected
- input - if it gets a non-numeric char, it puts the char back in the input
- buffer and returns. On the next pass, it finds that same char, still doesn't
- like it, so puts it back......
-
- A much better way to handle user input is to use fgets() to get the input into
- a buffer, then sscanf() or other functions to parse what's in the buffer -
- much safer, and easier to ask the user to try again.
-
- (NEVER use gets()!)
-
-
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
-
-
-
-
-
-
-